<?php

/*
Quad_Db_Table
Copyright (c) 2009 Ken Snyder
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/**
 * Class to build and execute queries agains a MySQL database
 */
class Quad_Db_Table {
	
	/**
	 * @var string  The name of the database table
	 */
	public $table;
	
	public $db;
	
	/**
	 * @param string $table  The name of ther database table
	 */
	public function __construct($table, $db = null) {
		$this->table = $table;
		if (!$db) {
			$db = Quad_Db::get();
		}
		$this->db = $db;
	}
	
	/**
	 * Convenient static method to create an instance
	 * 
	 * @return Quad_Db_Table
	 * @param object $table
	 * @example Quad_Db_Table::get('mytable')->insert($mydata);
	 */
	public static function get($table, $db = null) {		
		return new self($table, $db);
	}
	
	/**
	 * Build a simple select statement and execute
	 * @return array  Result set
	 * @param string|array $fields  String or array of field-value pairs representing the SELECT clause
	 * @param array $where[optional]  Field-value pairs to put into the where clause
	 * @param string|array  String or array of field names to add to the ORDER BY clause
	 * @param int|string  The number or string to insert following the LIMIT keyword
	 */
	public function select($fields, $where = array(), $orderBy = '', $limit = -1, $offset = 0) {			
		if (is_array($fields)) {
      $fields = join(', ', $this->_buildFieldList($fields));
		}
		if (is_array($orderBy)) {
			$orderBy = join(', ', $this->_buildFieldList($orderBy));
		}
		$bind = array();
		if (!empty($where)) {
			if (is_array($where)) {
				$bind = $where;
				$where = join(' AND ', $this->_buildCriteriaList($where));
			}
			$where = "WHERE $where";
		} else {
			$where = '';
		}
		$sql = "SELECT $fields FROM $this->table $where $orderBy";
//Quad_Debug::dumpdie($sql, $bind);		
		return $this->db->select($sql, $bind, $limit, $offset); 
	}
	
	/**
	 * Select the first result in a result set
	 * @return array  The result row
	 * @param string|array $fields  String or array of field-value pairs representing the SELECT clause
	 * @param array $where[optional]  Field-value pairs to put into the where clause
	 * @param string|array  String or array of field names to add to the ORDER BY clause
	 */
	public function selectFirst($fields, $where = array(), $orderBy = '') {
		$rs = $this->select($fields, $where, $orderBy, 1);
		return (isset($rs[0]) ? $rs[0] : false);
	}
	
	/**
	 * Build and execute an insert statement
	 * @return int|bool  The insert id if an auto-incremednt field or true on success, false on failure
	 * @param object $values  field-value pairs to insert
	 */
	public function insert($values) {
		$id = $this->db->insert($this->table, $values);
		return $id;
	}
	
	/**
	 * Build and execute an insert statement
	 * @return bool  True on success, false on failure
	 * @param object $values  field-value pairs to insert
	 * @param array $criteria  Field-value pairs to put into the where clause
	 * @return int  Number of rows affected
	 */	
  public function update($values, $criteria) {
    $rowsAffected = $this->db->update($this->table, $values, $criteria);
    return $rowsAffected;
  }	
  
  /**
   * Build and execute a delete statement
   * @param array $criteria  Field-value pairs to put into the where clause
   * @return int  Number of rows affected
   */
  public function delete($criteria) {
  	$rowsAffected = $this->db->delete($this->table, $criteria);
    return $rowsAffected;
  }
  
	/**
	 * Helper function to build criteria list
	 * @return array
	 * @param array $criteria  Field-value pairs to put into an SQL clause
	 */
  protected function _buildCriteriaList($criteria) {
    $fields = array();
    foreach ($criteria as $field => $value) {
    	if ($value === null) {
      	$fields[] = $this->db->quoteIdentifier($field) . " IS :$field";
    	}
    	else {
      	$fields[] = $this->db->quoteIdentifier($field) . " = :$field";
    	}
    }
    return $fields;
  }
  
	/**
	 * Helper function to build field list
	 * @return array
	 * @param array $fields  List of fied names
	 */
  public function _buildFieldList($fields) {
  	$fieldList = array();
    foreach ($fields as $field) {
      $fieldList[] = $this->db->quoteIdentifier($field);
    }
    return $fieldList;
  }
  
}